package cn.ywyself.extend.render;

import cn.ywyself.extend.utils.QrCodeUtils;
import com.google.zxing.WriterException;
import com.jfinal.kit.StrKit;
import com.jfinal.render.Render;
import com.jfinal.render.RenderException;

import java.io.IOException;
import java.io.OutputStream;

/**
 * 二维码生成
 *
 * @author : ywyself
 * @created : 2018-10-11 10:25
 */
public class YsQrCodeRender extends Render {
    /**
     * 二维码内容
     */
    private String text = "";
    /**
     * 二维码宽度
     */
    private int size = 250;
    /**
     * 二维码logo，为null时不使用logo
     */
    private String logoImagePath = "/qr/logo.png";

    private String backImagePath = null; // /qr/bg.png

    public YsQrCodeRender(String text) {
        if (StrKit.isBlank(text)) {
            throw new IllegalArgumentException("qrCode 内容不能为空");
        }
        this.text = text;
    }

    public YsQrCodeRender(String text, String logoImagePath) {
        this(text);
        this.logoImagePath = logoImagePath;
    }

    public YsQrCodeRender(String text, int size, String logoImagePath) {
        this(text, logoImagePath);
        this.size = size;
    }

    public YsQrCodeRender(String text, int size, String logoImagePath, String backImagePath) {
        this(text, size, logoImagePath);
        this.backImagePath = backImagePath;
    }

    public YsQrCodeRender(String text, String logoImagePath, String backImagePath) {
        this(text, logoImagePath);
        this.backImagePath = backImagePath;
    }

    /**
     * Render to client
     */
    @Override
    public void render() {
        OutputStream outputStream = null;
        try {
            response.setHeader("Pragma", "no-cache");    // HTTP/1.0 caches might not implement Cache-Control and might only implement Pragma: no-cache
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
            response.setContentType("image/png");

            outputStream = response.getOutputStream();
            QrCodeUtils.init()
                    .setText(this.text)
                    .setSize(this.size)
                    .setLogoImagePath(getFilePath(this.logoImagePath))
                    .setBackImagePath(getFilePath(this.backImagePath))
                    .write(outputStream);
            outputStream.flush();
        } catch (IOException | WriterException e) {
            e.printStackTrace();
            throw new RenderException(e);
        } finally {
            try {
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 获取文件地址（必须在调用render方法后才可使用）
     *
     * @param srcPath 文件在项目中的地址
     * @return 文件在系统中的地址
     */
    private String getFilePath(String srcPath) {
        return request.getSession().getServletContext().getRealPath(srcPath);
    }
}
